package com.snow.aspect;

import com.snow.service.log.LogService;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;


/*
切面日志
请求的日志处理
 */
@Aspect
@Component
public class WebAspectLog {
    @Autowired
    private LogService logService;
    private static Logger logger = Logger.getLogger(WebAspectLog.class);

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    @Pointcut("execution(public * com.snow.controller..*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        startTime.set(System.currentTimeMillis());

        //接收到请求，记录请求的内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();

        logger.info("URL==>" + request.getRequestURI());
        logger.info("HTTP_METHOD==>" + request.getMethod());
        logger.info("IP==>" + request.getRemoteAddr());
        logger.info("CLASS_METHOD==>" + request.getMethod() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS==>" + Arrays.toString(joinPoint.getArgs()));


    }

    @AfterReturning(returning = "res",pointcut = "log()")

    public void  doAfterReturning(Object res) throws Throwable{
        //处理完请求返回内容
        logger.info("RESULT==>" + res);
        logger.info("SPEND_TIME==>" + (System.currentTimeMillis() - startTime.get()));
        startTime.remove();//防止内存泄漏

    }
}
